import 'package:flutter/material.dart';

/// 扩展放这里
extension BuildContextExt on BuildContext {
  /// 获取当前组件的 RenderBox
  RenderBox? renderBox() {
    return findRenderObject() is RenderBox
        ? (findRenderObject() as RenderBox)
        : null;
  }

  /// 键盘是否可见
  bool get keyboardVisible => MediaQuery.of(this).viewInsets.bottom > 70;

  /// 当前组件相对位置在整个屏幕的位置
  Offset? position({Offset offset = Offset.zero}) {
    try {
      return renderBox()?.localToGlobal(offset);
    } catch (e) {
      return null;
    }
  }
}

extension GlobalKeyExt on GlobalKey {
  /// 获取当前组件的 RenderBox
  RenderBox? renderBox() => currentContext?.renderBox();

  /// 获取当前组件的 Position
  Offset? position({Offset offset = Offset.zero}) =>
      currentContext?.position(offset: offset);

  /// 获取当前组件的 Size
  Size? get size => currentContext?.size;
}

extension DateTimeExt on DateTime {
  /// 365天以前
  static DateTime lastYear() {
    var c = DateTime.now();
    return c.add(Duration(
        days: -365,
        hours: -c.hour,
        minutes: -c.minute,
        seconds: -c.second,
        milliseconds: -c.millisecond));
  }

  /// 30天以前
  static DateTime lastMonth() {
    var c = DateTime.now();
    return c.add(Duration(
        days: -30,
        hours: -c.hour,
        minutes: -c.minute,
        seconds: -c.second,
        milliseconds: -c.millisecond));
  }

  /// n天以前
  static DateTime dayBefore(int days) {
    var c = DateTime.now();
    return c.add(Duration(
        days: -days,
        hours: -c.hour,
        minutes: -c.minute,
        seconds: -c.second,
        milliseconds: -c.millisecond));
  }
}
